package com.lanou3g.dllo.baidumusic.musiclibrary.ranklist.ranklistdetail;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou3g.dllo.baidumusic.R;
import com.lanou3g.dllo.baidumusic.base.BaseFragment;
import com.lanou3g.dllo.baidumusic.database.MyFavorite;
import com.lanou3g.dllo.baidumusic.database.SingleLiteOrm;
import com.lanou3g.dllo.baidumusic.download.SingleDownload;
import com.lanou3g.dllo.baidumusic.event.IndexEvent;
import com.lanou3g.dllo.baidumusic.main.playmusic.PlaymusicBean;
import com.lanou3g.dllo.baidumusic.event.SongIdEvent;
import com.lanou3g.dllo.baidumusic.mine.myfavorite.MyFavoriteManager;
import com.lanou3g.dllo.baidumusic.tools.MyRvOnClickListener;
import com.lanou3g.dllo.baidumusic.tools.MyVolley;
import com.lanou3g.dllo.baidumusic.tools.OnRemoveListener;
import com.lanou3g.dllo.baidumusic.tools.PlaylistManager;
import com.lanou3g.dllo.baidumusic.tools.SingleVolley;
import com.litesuits.orm.db.assit.QueryBuilder;
import org.greenrobot.eventbus.EventBus;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.SaveListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by dllo on 16/6/22.
 */

public class RanklistDetailFragment extends BaseFragment {

    private RanklistDetailAdapter ranklistDetailAdapter;
    private RecyclerView ranklistdetailRecyclerview;
    private ImageView ranklistdetailTopPhoto;
    private TextView ranklistdetailTotalsongsTv;
    private ImageView ranklistdetailReturnBtn;
    private RanklistDetailBean ranklistDetailBean;
    private PopupWindow popupWindow;
    private MyFavorite myFavorite;

    @Override
    public int setLayout() {
        return R.layout.fragment_ranklistdetail;
    }

    @Override
    public void initView(View view) {
        ranklistdetailRecyclerview = (RecyclerView) view.findViewById(R.id.ranklistdetail_recyclerview);
        ranklistdetailTopPhoto = (ImageView) view.findViewById(R.id.ranklistdetail_top_photo);
        ranklistdetailTotalsongsTv = (TextView) view.findViewById(R.id.ranklistdetail_totalsongs_tv);
        ranklistdetailReturnBtn = (ImageView) view.findViewById(R.id.ranklistdetail_return_btn);
        ranklistdetailReturnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("RanklistDetailFragment")).commit();
                getFragmentManager().beginTransaction().show(getFragmentManager().findFragmentByTag("MainFragment")).commit();
            }
        });
    }

    @Override
    public void initData() {

        ranklistDetailAdapter = new RanklistDetailAdapter(context);
        int rankType = this.getArguments().getInt("rankType");
        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=" + rankType + "&format=json&offset=0&size=100&from=ios&fields=title,song_id,author,resource_type,havehigh,is_new,has_mv_mobile,album_title,ting_uid,album_id,charge,all_rate&version=5.2.1&from=ios&channel=appstore";
        MyVolley.getMyVolley().initGson(url, new MyVolley.GetGsonListener<RanklistDetailBean>() {
            @Override
            public void getGsonListener(RanklistDetailBean data) {
                ranklistDetailBean = data;
                ranklistDetailAdapter.setRanklistDetailBean(data);
                SingleVolley.getSingleVolley(context).getImageLoader().get(data.getBillboard().getPic_s210(),
                        ImageLoader.getImageListener(ranklistdetailTopPhoto, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
                String number = "共" + data.getSong_list().size() + "首歌";
                ranklistdetailTotalsongsTv.setText(number);
                ranklistdetailRecyclerview.setAdapter(ranklistDetailAdapter);
                ranklistdetailRecyclerview.setLayoutManager(new LinearLayoutManager(context));

            }
        }, RanklistDetailBean.class);

        ranklistDetailAdapter.setMyRvOnClickListener(new MyRvOnClickListener() {
            @Override
            public void onClick(int position) {
                String songId = ranklistDetailBean.getSong_list().get(position).getSong_id();
                EventBus.getDefault().post(new SongIdEvent(songId));
                EventBus.getDefault().post(new IndexEvent(position));
                PlaylistManager.getInstance().getPlaylist().clear();
                // 使播放列表获得歌单里的全部歌曲
                for (RanklistDetailBean.SongListBean bean : ranklistDetailBean.getSong_list()) {
                    PlaylistManager.getInstance().getPlaylist().add(new PlaymusicBean(bean.getSong_id(), bean.getAuthor(), bean.getTitle()));
                }
            }
        });

        // 弹出popwindow并进行收藏和下载分享
        ranklistDetailAdapter.setOnRemoveListener(new OnRemoveListener() {
            @Override
            public void onRemoveClick(int position) {
                popMore(ranklistDetailBean, position);
            }
        });
    }

    public void popMore(final RanklistDetailBean ranklistDetailBean, final int position) {

        View view = LayoutInflater.from(context).inflate(R.layout.item_recentlyplaypop, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置返回键可使popWindow退出
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        popupWindow.showAtLocation(ranklistdetailRecyclerview, Gravity.BOTTOM, 0, 0);
        ImageView popLove = (ImageView) view.findViewById(R.id.recentlyplay_love);
        ImageView popDownload = (ImageView) view.findViewById(R.id.recentlyplay_download);
        ImageView popShare = (ImageView) view.findViewById(R.id.recentlyplay_share);
        FrameLayout empty = (FrameLayout) view.findViewById(R.id.recentlyplay_replace);
        TextView popTitle = (TextView) view.findViewById(R.id.recentlyplay_poptitle);
        popTitle.setText(ranklistDetailBean.getSong_list().get(position).getTitle());

        // 获取当前bmobUser信息
        BmobUser bmobUser = BmobUser.getCurrentUser(context);
        if (bmobUser != null) {
            MyFavorite myFavorite = new MyFavorite();
            myFavorite.setUserName(bmobUser.getUsername());
            myFavorite.setTitle(ranklistDetailBean.getSong_list().get(position).getTitle());
            myFavorite.setAuther(ranklistDetailBean.getSong_list().get(position).getAuthor());
            myFavorite.setSongId(ranklistDetailBean.getSong_list().get(position).getSong_id());

            int number = 0;
            for (MyFavorite favorite : MyFavoriteManager.getInstance().getMyFavorites()) {
                if (favorite.getTitle().equals(myFavorite.getTitle())) {
                    number = number + 1;
                }
            }

            if (number == 0) {
                popLove.setImageResource(R.mipmap.pop_love_normal);
            } else {
                popLove.setImageResource(R.mipmap.pop_love_checked);
            }

        } else {
            QueryBuilder<MyFavorite> queryBuilderLocal = new QueryBuilder<>(MyFavorite.class);
            queryBuilderLocal.whereEquals("title", ranklistDetailBean.getSong_list().get(position).getTitle());
            if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilderLocal).size() == 0) {
                popLove.setImageResource(R.mipmap.pop_love_normal);
            } else {
                popLove.setImageResource(R.mipmap.pop_love_checked);
            }
        }

        // 点击空白处关闭popWindow
        empty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        // 喜欢的点击事件
        popLove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BmobUser bmobUser1 = BmobUser.getCurrentUser(context);
                if (bmobUser1 == null) {
                    addToLocal(position);
                    // 刷新我的界面我喜欢的单曲的歌曲数
                    Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
                    context.sendBroadcast(intent);
                } else {
                    addToInternet(ranklistDetailBean, position, bmobUser1);
                }
                popupWindow.dismiss();
            }
        });


        // 下载监听
        popDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SingleDownload.getSingleDownload().Download(ranklistDetailBean.getSong_list().get(position).getSong_id());
            }
        });

        // 分享监听
        popShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popupWindow.dismiss();

                ShareSDK.initSDK(context);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                oks.setTitle("分享");
                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                oks.setTitleUrl("http://sharesdk.cn");
                // text是分享文本，所有平台都需要这个字段
                oks.setText("项目测试文本");
                // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl("http://sharesdk.cn");
                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("项目测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite(getString(R.string.app_name));
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");
                // 启动分享GUI
                oks.show(context);
            }
        });

    }

    // 加入本地数据库
    public void addToLocal(int position) {
        QueryBuilder<MyFavorite> queryBuilder = new QueryBuilder<>(MyFavorite.class);
        queryBuilder.whereEquals("title", ranklistDetailBean.getSong_list().get(position).getTitle());
        if (SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder).size() == 0) {
            SingleLiteOrm.getSingleLiteOrm().getLiteOrm().insert(new MyFavorite(ranklistDetailBean.getSong_list()
                    .get(position).getSong_id(), ranklistDetailBean.getSong_list().get(position).getTitle(),
                    ranklistDetailBean.getSong_list().get(position).getAuthor()));
            Toast.makeText(context, "已添加到我喜欢的单曲", Toast.LENGTH_SHORT).show();
            // 刷新我的界面我喜欢的单曲的歌曲数
            Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
            context.sendBroadcast(intent);

        } else {
            SingleLiteOrm.getSingleLiteOrm().getLiteOrm().delete(SingleLiteOrm.getSingleLiteOrm().getLiteOrm().query(queryBuilder));
            Toast.makeText(context, "已取消喜欢", Toast.LENGTH_SHORT).show();
            // 内部取消喜欢时发送广播刷新我的界面我喜欢的单曲的歌曲数
            Intent intent = new Intent(context.getPackageName() + ".DELETEREFRESH");
            context.sendBroadcast(intent);
        }
        popupWindow.dismiss();
    }

    // 加入网络
    public void addToInternet(RanklistDetailBean ranklistDetailBean, int position, BmobUser bmobUser) {
        myFavorite = new MyFavorite();
        myFavorite.setUserName(bmobUser.getUsername());
        myFavorite.setTitle(ranklistDetailBean.getSong_list().get(position).getTitle());
        myFavorite.setAuther(ranklistDetailBean.getSong_list().get(position).getAuthor());
        myFavorite.setSongId(ranklistDetailBean.getSong_list().get(position).getSong_id());

        int number = 0;
        for (MyFavorite favorite : MyFavoriteManager.getInstance().getMyFavorites()) {
            if (favorite.getTitle().equals(myFavorite.getTitle())) {
                number = number + 1;
                myFavorite = favorite;
            }
        }

        if (number == 0) {
            myFavorite.save(context, new SaveListener() {
                @Override
                public void onSuccess() {
                    MyFavoriteManager.getInstance().getMyFavorites().add(myFavorite);
                    Toast.makeText(context, "已添加到我喜欢的单曲", Toast.LENGTH_SHORT).show();
                    // 刷新我的界面我喜欢的单曲的歌曲数
                    Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
                    context.sendBroadcast(intent);
                }

                @Override
                public void onFailure(int i, String s) {

                }
            });

        } else {
            myFavorite.delete(context, new DeleteListener() {
                @Override
                public void onSuccess() {
                    MyFavoriteManager.getInstance().getMyFavorites().remove(myFavorite);
                    Toast.makeText(context, "已取消喜欢", Toast.LENGTH_SHORT).show();
                    // 刷新我的界面我喜欢的单曲的歌曲数
                    Intent intent = new Intent(context.getPackageName() + ".REFRESHMYFAVORITE");
                    context.sendBroadcast(intent);
                }

                @Override
                public void onFailure(int i, String s) {

                }
            });
        }
    }

}
